<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园订餐系统管理员界面</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <!-- jqgrid-->
    <link href="css/plugins/jqgrid/ui.jqgrid.css?0820" rel="stylesheet">
    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css?v=4.1.0" rel="stylesheet">

    <!-- 引入 Moment.js CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <style>
        /* Additional style to fix warning dialog position */
        #alertmod_table_list_2 {
            top: 900px !important;
        }

        .btn-primary,
        .btn-primary:hover,
        .btn-primary:active,
        .btn-primary:focus {
            background-color: transparent;
            border: none;
            color: #000000;
            padding: 0;
            box-shadow: none; /* 禁用按钮的阴影效果 */
            outline: none; /* 禁用点击时的轮廓线 */
        }
    </style>
</head>
<body class="gray-bg" th:with="consumerId=${session.user}">
<input type="hidden" id="hiddenConsumerId" th:value="${consumerId}">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox ">
                <div class="ibox-title">
                    <h5>校园订餐系统菜单列表</h5>
                </div>
                <div class="ibox-content">
                    <div class="jqGrid_wrapper">
                        <table id="table_list_2">
                            <thead>
                            <tr>
                                <th>菜品id</th>
                                <th>窗口id</th>
                                <th>菜单id</th>
                                <th>菜品名</th>
                                <th>价格</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="alertmod_table_list_2">
                            <!-- 使用Thymeleaf迭代数据 -->
                            <tr th:each="dish : ${data}">
                                <td th:text="${dish.dish_id}"></td>
                                <td th:text="${dish.window_id}"></td>
                                <td th:text="${dish.menu_id}"></td>
                                <td th:text="${dish.dish_name}"></td>
                                <td th:text="${dish.price}"></td>
                                <td>
                                    <!-- 在每一行的最后一个单元格中添加操作按钮 -->
                                    <button class="btn btn-primary" onclick="submitOrderForDish('${dish.dish_id}', '${dish.window_id} ','${dish.dish_name}', '${dish.price}', '${consumerId}')">订餐</button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <div id="pager_list_2"></div>
                    </div>
                    <!-- 添加此div以显示警告消息 -->
                    <div id="alertMessage" class="alert" style="display:none;"></div>
                    <button class="btn btn-success" onclick="refreshData()">刷新</button>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 模态框 -->
<div class="modal fade" id="orderModal" tabindex="-1" role="dialog" aria-labelledby="orderModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="orderModalLabel">填写订单信息</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="orderForm">
                    <div class="form-group">
                        <label for="dish_id">菜品ID:</label>
                        <!-- 在模态表单内添加这些隐藏字段 -->
<!--                        <input type="hidden" id="consumer_id" th:value="${consumerId}">-->
                        <input type="text" class="form-control" id="dish_id" readonly>
                    </div>
                    <div class="form-group">
                        <label for="window_id">窗口ID:</label>
                        <input type="text" class="form-control" id="window_id" readonly>
                    </div>
                    <div class="form-group">
                        <label for="dish_name">菜品名:</label>
                        <input type="text" class="form-control" id="dish_name" readonly>
                    </div>
                    <div class="form-group">
                        <label for="price">价格:</label>
                        <input type="text" class="form-control" id="price" readonly>
                    </div>
                    <div class="form-group">
                        <label for="quantity">数量:</label>
                        <input type="number" class="form-control" id="quantity" value="1" min="1" oninput="calculateTotalPrice()">
                    </div>
                    <div class="form-group">
                        <label for="total">总价:</label>
                        <span id="total" class="form-control" readonly></span>
                    </div>
                    <div class="form-group">
                        <label for="pickup_time">取餐时间:</label>
                        <select id="pickup_time" class="form-control">
                            <option value="10:00">10:00</option>
                            <option value="12:00">12:00</option>
                            <!-- 添加更多选项 -->
                        </select>
                    </div>
                    <!-- 其他订单信息字段可以继续添加 -->
                    <!-- 提示信息 -->
                    <div id="orderAlert" class="alert alert-danger" style="display:none;"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitOrder()">提交订单</button>
            </div>
        </div>
    </div>
</div>
<!-- 全局js -->
<script src="js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js?v=3.3.6"></script>
<!-- jqGrid -->
<script src="js/plugins/jqgrid/i18n/grid.locale-cn.js?0820"></script>
<script src="js/plugins/jqgrid/jquery.jqGrid.min.js?0820"></script>
<!-- 自定义js -->
<script src="js/content.js?v=1.0.0"></script>
<!-- 引入 Moment.js CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<!-- Page-Level Scripts -->
<script>
    // 全局函数，用于显示警告信息
    function showAlert(message, alertType) {
        // 显示带有淡入淡出效果的警告
        $('#alertMessage').removeClass().addClass('alert ' + alertType).html(message).fadeIn().delay(3000).fadeOut();
    }

    // 全局函数，用于显示成功信息
    function showSuccessAlert(message) {
        showAlert(message, 'alert-success');
    }

    // 全局函数，用于显示错误信息
    function showErrorAlert(message) {
        showAlert(message, 'alert-danger');
    }
</script>
<script>
    // 确保页面加载完毕后再绑定事件
    $(document).ready(function () {

        // 提交订单函数
        window.submitOrderForDish = function (dishId,windowId, dishName, price) {
            // 在这里执行订餐按钮点击后的操作
            // 例如，显示模态框，填充相关信息
            var consumerId = $('#hiddenConsumerId').val(); // 通过隐藏字段获取 consumerId

            $('#dish_id').val(dishId);
            $('#window_id').val(windowId);  // 设置 window_id 的值
            $('#dish_name').val(dishName);
            $('#price').val(price);
            $('#consumer_id').val(consumerId); // 设置 consumer_id 的值

            // 显示模态框
            $('#orderModal').modal('show');
        };
    });


    $(document).ready(function () {
        $.jgrid.defaults.styleUI = 'Bootstrap';
        // 初始化jqGrid的函数
        function initJqGrid(data) {
            console.log('正在使用数据初始化 jqGrid：', data);

            $("#table_list_2").jqGrid({
                datatype: "local",
                data: data,
                height: 450,
                autowidth: true,
                shrinkToFit: true,
                rowNum: 20,
                rowList: [10, 20, 30],
                colNames: ['菜品id', '窗口id','菜单id', '菜品名', '价格', '操作'],
                colModel: [
                    { name: "dish_id", index: "dish_id", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "window_id", index: "window_id", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "menu_id", index: "menu_id", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "dish_name", index: "dish_name", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "price", index: "price", editable: true, width: 60, sorttype: "string", search: true },
                    {
                        name: "操作", width: 80, align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            // 返回一个包含按钮的字符串
                            return '<button class="btn btn-primary" onclick="submitOrderForDish(\'' +
                                rowObject.dish_id + '\', \'' + rowObject.window_id + '\', \'' + rowObject.dish_name + '\', \'' + rowObject.price + '\')">订餐</button>';
                        }
                    }
                ],
                pager: "#pager_list_2",
                viewrecords: true,
                caption: "菜单详细信息",


            });

            // Add selection
            $("#table_list_2").setSelection(4, true);
            // Setup buttons
            $("#table_list_2").jqGrid('navGrid', '#pager_list_2', {
                edit: true,
                add: true,
                del: true,
                search: true
            }, {
                height: 200,
                reloadAfterSubmit: true
            });
            console.log('jqGrid 初始化成功。');
        }

        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/backend-api-endpoint/getAllDishs',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 初始化jqGrid
                initJqGrid(data);
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    });

    // 刷新数据函数
    function refreshData() {
        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/backend-api-endpoint/getAllDishs',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 清空表格数据
                $("#table_list_2").jqGrid('clearGridData');
                // 添加新数据
                for (var i = 0; i < data.length; i++) {
                    $("#table_list_2").jqGrid('addRowData', i + 1, data[i]);
                }

                console.log('Data refreshed successfully.');
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    }
    var formattedPickupTime;

    <!-- 提交订单模态框函数 -->
    function getFormattedPickupTime() {
        var selectedPickupTime = $("#pickup_time option:selected").val();
        // 使用 Moment.js 格式化日期
        var formattedDate = moment().format('YYYY-MM-DD');
        // 组合日期和时间，注意只有一个日期部分
        var formattedDateTime = formattedDate + ' ' + selectedPickupTime;
        // 使用 Moment.js 验证格式是否正确
        var isValidFormat = moment(formattedDateTime, 'YYYY-MM-DD HH:mm').isValid();
        if (!isValidFormat) {
            console.error('日期时间格式不正确！');
            // 在这里处理日期时间格式不正确的情况，可以显示错误提示等
            return null;
        }
        // 修改日期时间格式
        var formattedDateTimeWithSeconds = moment(formattedDateTime, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm:ss');
        console.log('formattedPickupTime:', formattedDateTimeWithSeconds);
        return formattedDateTimeWithSeconds;
    }
    // 提交订单函数
    function submitOrder() {
        // 获取表单数据
        var quantity = $("#quantity").val();
        var price = $("#price").val();
        // 将字符串转换为数字
        quantity = parseInt(quantity);
        price = parseFloat(price);
        var total = quantity * price;

        // 更新 span 中的总价
        $('#total').text(total.toFixed(2));  // 使用toFixed确保小数点后两位
        var window_id = $("#window_id").val();

        var dish_name = $("#dish_name").val();
        var pickup_time = getFormattedPickupTime();
        var consumer_id = $("#hiddenConsumerId").val();

        // 添加检查，确保 pickup_time 不为空
        if (!pickup_time) {
            console.error('取餐时间为空！');
            // 在这里处理取餐时间为空的情况，可以显示错误提示等
            return;
        }

        // 设置 formattedPickupTime 的值
        formattedPickupTime = pickup_time;

        var reservation = {
            window_id: window_id,  // 设置 window_id 的值
            consumer_id: consumer_id,
            dish_name: dish_name,
            quantity: quantity,
            price: price,
            pickup_time: formattedPickupTime,
            total: total,
            // 根据需要添加其他订单信息
        };

        // 发送数据到后端
        $.ajax({
            url: '/backend-api-endpoint/placeOrder',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(reservation),
            success: function (response) {
                console.log(response);
                // 隐藏模态框
                $('#orderModal').modal('hide');
                // 显示成功提示
                showSuccessAlert('已为您创建订单，请到订单界面查看详细信息');
            },
            error: function (error) {
                console.error('下单错误:', error);
                // 输出服务器返回的错误消息
                console.error('服务器错误消息:', error.responseText);
                // 显示下单失败的提示
                showErrorAlert('下单失败，请重试。');
            }
        });
    }
    function formatDate(date, time) {
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        var hours = String(time.split(':')[0]).padStart(2, '0');
        var minutes = String(time.split(':')[1]).padStart(2, '0');
        var seconds = "00";
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    function calculateTotalPrice() {
        var quantity = parseInt($("#quantity").val()) || 0;
        var price = parseFloat($("#price").val()) || 0;
        var total = quantity * price;
        $('#total').text(total.toFixed(2));
    }
</script>
</body>
</html>
